package com.minisoft.online;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class PressureTest {

    private static final String URL = "http://172.16.52.93:11035/api/service/68e497cdbc7744e7be4b6974eb91f709/unit/103/5b417c8b5479423abb98f1e28e622deb/house";
    private static final int TOTAL_REQUESTS = 1000; // 总请求次数
    private static final int THREAD_COUNT = 2;    // 并发线程数

    public static void main(String[] args) throws Exception {
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();

        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger failureCount = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(TOTAL_REQUESTS);

        long startTime = System.currentTimeMillis();

        for (int i = 0; i < TOTAL_REQUESTS; i++) {
            HttpGet request = new HttpGet(URL);
            // 设置请求头
            request.setHeader("Host", "efang.cnhuafas.com");
            request.setHeader("AuthToken", "null");
            request.setHeader("Accept", "application/json, text/plain, */*");
            request.setHeader("Ticket", "4bbaac8502a74a619590e58546f635a8");
            request.setHeader("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJCMUEzODc2QUUiLCJhdWRpZW5jZSI6IndlYiIsImNyZWF0ZWQiOjE3NDU2NDAyMTc3OTUsImV4cCI6MTc0NjI0NTAxN30.atTK89gsn5IDz8D0Ls7QHr5fzIGUVW6jOztjVZYh7QTtVkKxR9zI8i1MN-47khND8FukCQkT-lcn8Cw7BGDq6g");
            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090b13) XWEB/9185 Flue");
            request.setHeader("Origin", "http://efang.cnhuafas.com");
            request.setHeader("Referer", "http://efang.cnhuafas.com/cs-chat/");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Cookie", "Hm_lvt_898dd24851f9153288ea57fc0d752418=1720164058,1720667303,1721092453,1721179444; Hm_lpvt_898dd24851f9153288ea57fc0d752418=1721179444; HMACCOUNT=263135C50A989DF5");
            request.setHeader("Content-Type", "application/json;charset=UTF-8");
            request.setHeader("Connection", "keep-alive");

            httpClient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse response) {
                    try {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            successCount.incrementAndGet();
                            // 如果需要查看响应内容，可以取消下面的注释
                             String responseBody = EntityUtils.toString(response.getEntity());
                             System.out.println("Response: " + responseBody);
                        } else {
                            failureCount.incrementAndGet();
                            System.err.println("Request failed with status code: " + statusCode);
                        }
                    } catch (Exception e) {
                        failureCount.incrementAndGet();
                        System.err.println("Error processing response: " + e.getMessage());
                    } finally {
                        latch.countDown();
                    }
                }

                @Override
                public void failed(Exception ex) {
                    failureCount.incrementAndGet();
                    System.err.println("Request failed: " + ex.getMessage());
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    failureCount.incrementAndGet();
                    System.err.println("Request cancelled");
                    latch.countDown();
                }
            });

            // 控制并发速率
            if (i % THREAD_COUNT == 0) {
                Thread.sleep(100);
            }
        }

        latch.await();
        httpClient.close();

        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        double qps = (double) TOTAL_REQUESTS / (totalTime / 1000.0);

        System.out.println("压测结果:");
        System.out.println("总请求数: " + TOTAL_REQUESTS);
        System.out.println("成功请求数: " + successCount.get());
        System.out.println("失败请求数: " + failureCount.get());
        System.out.println("总耗时(ms): " + totalTime);
        System.out.println("QPS(每秒请求数): " + String.format("%.2f", qps));
    }
}